import { ref } from 'vue'
import store from '@/app/store'
import { config, tax, signer, addSigner, client, addClient, updateClient } from '@/api/provider/fiskaly'
import index from '../../index'

// 初始化
const fiskalyStore = store()

// 加载
fiskalyStore.get = () => {
  return new Promise((resolve, reject) => {
    config().then(res => {
      if(res) {
        fiskalyStore.setData(res)
        return resolve(res)
      }
      reject(res)
    }).catch(err => {
      reject(err)
    })
  })
}

// 更新 
fiskalyStore.update = (data) => {
  return new Promise((resolve, jeject) => {
    config(data).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

fiskalyStore.tax = ref(false)
fiskalyStore.taxLoading = ref(false)
fiskalyStore.getTax = () => {
  return new Promise((resolve, jeject) => {
    fiskalyStore.taxLoading.value = true
    tax().then(res => {
      fiskalyStore.tax.value = res
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      fiskalyStore.taxLoading.value = false
    })
  })
}

fiskalyStore.signer = ref([])
fiskalyStore.signerLoading = ref(false)
fiskalyStore.getSigner = () => {
  return new Promise((resolve, jeject) => {
    fiskalyStore.signerLoading.value = true
    signer().then(res => {
      fiskalyStore.signer.value = res
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      fiskalyStore.signerLoading.value = false
    })
  })
}

fiskalyStore.addSigner = () => {
  return new Promise((resolve, jeject) => {
    addSigner().then(res => {
      fiskalyStore.getSigner()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

fiskalyStore.client = ref([])
fiskalyStore.clientLoading = ref(false)
fiskalyStore.getClient = () => {
  return new Promise((resolve, jeject) => {
    fiskalyStore.clientLoading.value = true
    client().then(res => {
      fiskalyStore.client.value = res
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      fiskalyStore.clientLoading.value = false
    })
  })
}

fiskalyStore.addClient = () => {
  return new Promise((resolve, jeject) => {
    addClient().then(res => {
      fiskalyStore.getClient()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

fiskalyStore.updateClient = id => {
  return new Promise((resolve, jeject) => {
    updateClient(id).then(res => {
      fiskalyStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default fiskalyStore